package fun.liuyu2783.txmessage.trade.mq;

import com.alibaba.fastjson.JSON;
import fun.liuyu2783.txmessage.common.MqConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;

@Slf4j
@RocketMQTransactionListener(txProducerGroup =  MqConstant.TRADE_TRANSACTION_PRODUCER_GROUP)
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {

    /**
     * 执行本地事务
     * @param message
     * @param o
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        String txId = (String)message.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        log.info("执行本地事务. txId={}, body={}", txId, JSON.toJSONString(message.getPayload()));
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 回查本地状态
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String txId = (String)message.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        log.info("回查本地状态. txId={}, body={}", txId, JSON.toJSONString(message.getPayload()));
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
